import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/config/config.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/user/login/binding.dart';
import 'package:flutter_smart_heating/pages/user/login/widget/agreement.dart';
import 'package:flutter_smart_heating/pages/user/login/widget/input_item.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key, this.title, this.isReady = false});
  final String? title;
  final bool isReady;

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Fluwx fluwx = Fluwx();
  TextEditingController usernameController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  FocusNode usernameFocusNode = FocusNode();
  FocusNode codeFocusNode = FocusNode();
  bool submitting = false;
  bool isAgree = false;
  bool isShowVerifyLogin = false;
  bool isReady = false;
  bool isWechatInstalled = false;
  ValueNotifier keyboardVisible = ValueNotifier<bool>(false);
  @override
  void initState() {
    super.initState();

    isReady = widget.isReady;

    KeyboardVisibilityController().onChange.listen((bool visible) async {
      if (!visible) {
        await 0.5.delay();
      }
      keyboardVisible.value = visible;
    });

    // 微信登陆回调
    fluwx.addSubscriber((response) async {
      if (response is WeChatAuthResponse) {
        var res = await Http.instance.post(
          '/plugin/sign_in_with_wechat/api/login_for_app',
          data: {
            "state": response.state,
            "code": response.code,
          },
        );
        setState(() {
          submitting = false;
        });
        if (res.code == 1) {
          signInWithToken(res.data['token']);
        } else if (res.code == -1) {
          bindWithThirdPartyUserId(res.data['third_party_user_id']);
        } else {
          Ui.toast(res.msg);
        }
      }
    });
    fluwx.isWeChatInstalled.then((value) {
      setState(() {
        isWechatInstalled = value;
      });
    });
  }

  @override
  void dispose() {
    usernameFocusNode.unfocus();
    codeFocusNode.unfocus();
    fluwx.clearSubscribers();
    super.dispose();
  }

  Future<bool> isAgreeToGoOn() async {
    if (!isAgree) {
      var result = await Get.dialog(const AgreementDialog());
      if (result == null) {
        return false;
      }
    }
    return true;
  }

  /// 提交登录
  submitLogin() async {
    usernameFocusNode.unfocus();
    codeFocusNode.unfocus();
    if (!await isAgreeToGoOn()) {
      return false;
    }
    if (usernameController.text == '') {
      return Ui.toast('请先输入手机号码');
    }
    if (codeController.text == '') {
      return Ui.toast('请先输入验证码');
    }
    setState(() {
      isAgree = true;
      submitting = true;
    });

    signInWithToken("12121");

    // var res = await Http.instance
    //     .post('/api/user/public/verificationCodeLogin', data: {
    //   'username': usernameController.text,
    //   'verification_code': codeController.text,
    // });

    // if (res.code == 1) {
    //   signInWithToken(res.data['token']);
    // } else {
    //   Ui.toast(res.msg);
    //   setState(() {
    //     submitting = false;
    //   });
    // }
  }

  /// 通过token置换用户信息
  signInWithToken(token) async {
    await AuthService.instance.login(token);
    Get.offAndToNamed('/');

    /// Get.back(result: await AuthService.instance.login(token));
  }

  /// 第三方登录绑定帐号
  bindWithThirdPartyUserId(id) async {
    var res = await App.pushRoute(
      context,
      BindingAccountPage(
        thirdPartyUserId: id,
      ),
      fullscreenDialog: true,
    );
    if (res == true) {
      Get.back(result: res);
    }
  }

  bool get isAllowToClicked =>
      usernameController.text.isNotEmpty && codeController.text.isNotEmpty;

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvoked: (back) {},
      child: KeyboardDismissOnTap(
        child: Scaffold(
          extendBodyBehindAppBar: true,
          appBar: AppBar(
            leading: Container(),
            backgroundColor: UiTheme.of(context)
                .matchColor(Colors.white, Colors.black)
                .withOpacity(0),
          ),
          body: UiLifeCycle(
            onRouteDone: () {
              setState(() {
                isReady = true;
              });
            },
            child: AnimatedSwitcher(
              duration: kThemeAnimationDuration,
              child: isShowVerifyLogin
                  ? Container()
                  : SingleChildScrollView(
                      padding: const EdgeInsets.symmetric(horizontal: 25),
                      child: SafeArea(
                        child: Center(
                          child: Container(
                            constraints: const BoxConstraints(maxWidth: 480),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: Get.size.width * 0.05),
                                Center(
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(30),
                                    child: Image.asset(
                                      'res/images/launcher_icon.png',
                                      width: 100,
                                      height: 100,
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 10),
                                const Center(
                                  child: Text(
                                    Config.appName,
                                    style: TextStyle(fontSize: 20),
                                  ),
                                ),
                                const SizedBox(height: 40),
                                InputItemView(
                                  render: isReady,
                                  controller: usernameController,
                                  focusNode: usernameFocusNode,
                                  placeholder: '请输入手机号码',
                                  onChanged: (value) {
                                    setState(() {
                                      isAllowToClicked;
                                    });
                                  },
                                  icon: UiIcons.mobile,
                                ),
                                InputItemView(
                                  render: isReady,
                                  controller: codeController,
                                  focusNode: codeFocusNode,
                                  placeholder: '请输入验证码',
                                  maxLength: 6,
                                  keyboardType: TextInputType.number,
                                  onChanged: (value) {
                                    setState(() {
                                      isAllowToClicked;
                                    });
                                  },
                                  icon: UiIcons.safetycertificate,
                                  suffix: UiVerificationCode(
                                    account: () => usernameController.text,
                                  ),
                                ),
                                Container(
                                  alignment: Alignment.centerLeft,
                                  child: AgreementView(
                                    fontSize: 14,
                                    isAgree: isAgree,
                                    iconCheckedColor: UiTheme.primary,
                                    onTap: (value) {
                                      setState(() {
                                        isAgree = value;
                                      });
                                    },
                                  ),
                                ),
                                const SizedBox(height: 30),
                                SizedBox(
                                  width: double.infinity,
                                  height: UiTheme.buttonHeight,
                                  child: UiButton(
                                    onPressed: submitLogin,
                                    loading: submitting,
                                    disabled: !isAllowToClicked,
                                    child: Text(
                                      '立即登录'.tr,
                                      style:
                                          const TextStyle(color: Colors.white),
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 15),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
            ),
          ),
          bottomNavigationBar: bottomView(),
        ),
      ),
    );
  }

  SafeArea bottomView() {
    return SafeArea(
      bottom: true,
      top: false,
      minimum: const EdgeInsets.only(bottom: 20),
      child: ValueListenableBuilder(
        valueListenable: keyboardVisible,
        builder: (context, state, widget) {
          return AnimatedSwitcher(
            duration: kThemeAnimationDuration,
            child: state || submitting
                ? const SizedBox.shrink()
                : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      if (Platform.isIOS)
                        SignInWithAppleBuilder(builder: (_) {
                          return UiTap(
                            onTap: () async {
                              if (!await isAgreeToGoOn()) {
                                return false;
                              }
                              setState(() {
                                isAgree = true;
                                submitting = true;
                              });
                              try {
                                final credential =
                                    await SignInWithApple.getAppleIDCredential(
                                  scopes: [
                                    AppleIDAuthorizationScopes.email,
                                    AppleIDAuthorizationScopes.fullName,
                                  ],
                                  nonce: 'example-nonce',
                                  state: 'sign_in_with_apple',
                                );

                                var res = await Http.instance.post(
                                  '/plugin/sign_in_with_apple/api/login_for_app',
                                  data: {
                                    "userIdentifier": credential.userIdentifier,
                                    "identityToken": credential.identityToken,
                                    "email": credential.email ?? '',
                                    "familyName": credential.familyName ?? '',
                                    'givenName': credential.givenName ?? '',
                                    "authorizationCode":
                                        credential.authorizationCode,
                                    "state": credential.state
                                  },
                                );

                                if (res.code == 1) {
                                  signInWithToken(res.data['token']);
                                } else if (res.code == -1) {
                                  bindWithThirdPartyUserId(
                                      res.data['third_party_user_id']);
                                } else {
                                  Ui.toast(res.msg);
                                }
                              } catch (error) {
                                if (error.toString().contains('unknown')) {
                                  Ui.toast('Apple登录不可用');
                                }
                              }

                              setState(() {
                                submitting = false;
                              });
                            },
                            child: const Padding(
                              padding: EdgeInsets.all(10.0),
                              child: CircleAvatar(
                                radius: 20,
                                backgroundColor: Colors.black,
                                child: Padding(
                                  padding: EdgeInsets.only(bottom: 3),
                                  child: Icon(
                                    UiIcons.apple_fill,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          );
                        }),
                      if (isWechatInstalled)
                        UiTap(
                          onTap: () async {
                            if (!await isAgreeToGoOn()) {
                              return false;
                            }
                            setState(() {
                              isAgree = true;
                              submitting = true;
                            });
                            await fluwx.authBy(
                              which: NormalAuth(
                                scope: 'snsapi_userinfo',
                                state: 'sign_in_with_wechat',
                              ),
                            );
                            setState(() {
                              submitting = false;
                            });
                          },
                          child: const Padding(
                            padding: EdgeInsets.all(10.0),
                            child: CircleAvatar(
                              radius: 20,
                              backgroundColor: Color.fromARGB(255, 7, 193, 90),
                              child: Padding(
                                padding: EdgeInsets.only(bottom: 3),
                                child: Icon(
                                  UiIcons.wechat_fill,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
          );
        },
      ),
    );
  }
}
